<template>
	<view class="container">
		<!-- 原有内容保持不变 -->
		<view class="title">蓝牙设备绑定</view>
		<view class="selector">
			<text class="label">楼栋：</text>
			<view>
				<picker mode="selector" :range="buildings" range-key="name" @change="bindBuildingChange">
					<view class="picker">{{ selectedBuilding.name || '请选择楼栋' }}</view>
				</picker>
			</view>
		</view>
		<view class="selector">
			<text class="label">楼层：</text>
			<picker mode="selector" :range="filteredFloors" range-key="layer" @change="bindFloorChange">
				<view class="picker">{{ selectedFloor.layer || '请选择楼层' }}</view>
			</picker>
		</view>
		<view class="selector">
			<text class="label">房间号：</text>
			<picker mode="selector" :range="filteredRooms" range-key="number" @change="bindRoomChange">
				<view class="picker">{{ selectedRoom.number || '请选择房间号' }}</view>
			</picker>
		</view>
		<button class="binding-button" @click="findDevice">搜索设备</button>

		<radio-group v-if="devices.watermeter" v-model="selectedDevice" @change="radiochange">
			<view v-for="(item, index) in devices.watermeter" :key="item.id" class="device-item">
				<radio :value="item.id" />
				设备号: {{ item.meterNumber }} 热水设备
			</view>
			<view v-for="(item, index) in devices.colewatermeter" :key="item.id" class="device-item">
				<radio :value="item.id" />
				设备号: {{ item.meterNumber }} 冷水设备
			</view>
		</radio-group>

		<button class="binding-button" @click="bindDevice">绑定设备</button>

		<!-- 1. 新增 Flex 容器包裹开/关按钮，控制同行排列 -->
		<view class="switch-btn-group">
			<button class="switch-btn" @click="turnOn">开</button>
			<button class="switch-btn" @click="turnOff">关</button>
		</view>
	</view>
</template>

<script>
	// JS 部分无修改，保持原有逻辑
	import {
		ajax
	} from '../../utils/request.js';
	export default {
		data() {
			return {
				bluetoothId: '',
				selectedBuilding: {},
				selectedFloor: {},
				selectedRoom: {},
				bluetoothName: '',
				bindData: [],
				buildings: [],
				filteredFloors: [],
				filteredRooms: [],
				devices: {},
				selectedDevice: '',
				selectedDeviceCode: null,
				id: '',
				loading: true,
				cacheExpiration: 24 * 60 * 60 * 1000,
			};
		},
		created() {
			const localDevice = uni.getStorageSync('selectedDevice') || {};
			this.bluetoothId = localDevice.deviceId || 'default-bluetooth-id';
			this.bluetoothName = localDevice.name || 'default-bluetooth-name';

			// 2. 调用 loadFromCache 加载缓存（替换原有手动判断缓存的逻辑）
			this.loadFromCache();
		},
		methods: {
			loadFromCache() {
				try {
					const cachedData = uni.getStorageSync('bindData');
					const cacheTime = uni.getStorageSync('bindDataTime');
					const currentTime = new Date().getTime();

					if (cachedData && cacheTime && (currentTime - cacheTime < this.cacheExpiration)) {
						console.log("剩余时间", currentTime - cacheTime)
						console.log('使用缓存数据');
						this.bindData = cachedData;
						this.buildings = cachedData.builds;
						this.loading = false;
					} else {
						console.log('缓存不存在或已过期，请求新数据');
						this.fetchFormData();
					}
				} catch (error) {
					console.error('缓存读取失败:', error);
					this.fetchFormData();
				}
			},
			radiochange(e) {
				this.id = e.detail.value;
				const selectedDeviceId = e.detail.value;

				const selectedHotWaterDevice = this.devices.watermeter.find(device => device.id == selectedDeviceId);
				if (selectedHotWaterDevice) {
					this.selectedDeviceCode = selectedHotWaterDevice.code;
				}

				const selectedColdWaterDevice = this.devices.colewatermeter.find(device => device.id == selectedDeviceId);
				if (selectedColdWaterDevice) {
					this.selectedDeviceCode = selectedColdWaterDevice.code;
				}

				console.log('选择的id', this.selectedDeviceCode);
			},
			fetchFormData() {
				this.loading = true;
				ajax('/api/meter/bindinfo', 'POST', {}).then(data => {
					this.bindData = data.data;
					this.buildings = data.data.builds;
					uni.setStorageSync('bindData', data.data);
					uni.setStorageSync('bindDataTime', new Date().getTime());
					this.loading = false;
				}).catch(error => {
					console.error('请求失败:', error);
					this.loading = false;
					uni.showToast({
						title: '数据加载失败',
						icon: 'none'
					});
				});
			},
			bindBuildingChange(e) {
				this.selectedBuilding = this.buildings[e.target.value];
				this.selectedFloor = {};
				this.selectedRoom = {};
				this.filteredFloors = this.bindData.foorls.filter(floor => floor.buildingId === this.selectedBuilding.id);
				this.filteredRooms = [];
			},
			bindFloorChange(e) {
				this.selectedFloor = this.filteredFloors[e.target.value];
				this.selectedRoom = {};
				this.filteredRooms = this.bindData.rooms.filter(room => room.buildingId === this.selectedBuilding.id &&
					room.floorId === this.selectedFloor.id);
			},
			bindRoomChange(e) {
				this.selectedRoom = this.filteredRooms[e.target.value];
			},
			findDevice() {
				if (this.selectedRoom.SS_MC) {
					console.log("选中的房间", this.selectedRoom.SS_MC);
					ajax('/api/meter/querywater', 'POST', {
						SS_MC: this.selectedRoom.SS_MC
					}).then(data => {
						this.devices = data.data;
					}).catch(error => {
						console.error('请求失败:', error);
					});
				} else {
					uni.showToast({
						title: '请选择房间',
						icon: 'none'
					});
				}
			},
			bindDevice() {
				const data = {
					bluetoothName: this.bluetoothName,
					id: this.id,
					code: this.selectedDeviceCode,
					deviceType: this.devices.watermeter.some(device => device.id == this.id) ? 'hot' : 'cold'
				};
				if (uni.getSystemInfoSync().platform == 'ios') {
					data.IOSUUID = this.bluetoothId;
				} else {
					data.UUID = this.bluetoothId;
				}
				if (data.id && (data.UUID || data.IOSUUID)) {
					ajax('/api/meter/bindwatermeter', 'POST', data).then(response => {
						uni.showToast({
							title: '设备绑定成功！',
							icon: 'success'
						});
						console.log(data);
					}).catch(error => {
						uni.showToast({
							title: '设备绑定失败！',
							icon: 'none'
						});
					});
				} else {
					uni.showToast({
						title: '请选择房间和设备',
						icon: 'none'
					});
				}
			},
			turnOn() {
				console.log("设备已打开")
				uni.showToast({
					title: '设备已开启',
					icon: 'success'
				}); // 新增反馈提示
			},
			turnOff() {
				console.log("设备已关闭")
				uni.showToast({
					title: '设备已关闭',
					icon: 'success'
				}); // 新增反馈提示
			}
		}
	};
</script>

<style scoped>
	/* 原有样式保持不变 */
	.container {
		padding: 20px;
		background-color: #f8f8f8;
	}

	.title {
		font-size: 18px;
		color: #333;
		text-align: center;
		margin-bottom: 20px;
	}

	.selector {
		display: flex;
		align-items: center;
		justify-content: space-around;
		margin-bottom: 15px;
	}

	.label {
		width: 70px;
		font-size: 16px;
		color: #666;
		text-align: right;
		margin-right: -30px;
	}

	.picker {
		background-color: #ffffff;
		padding: 10px;
		border-radius: 5px;
		font-size: 16px;
		color: #666;
		min-width: 200px;
		flex-grow: 1;
	}

	.device-item {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
	}

	.binding-button {
		background-color: #007aff;
		color: #ffffff;
		padding: 10px 20px;
		border: none;
		border-radius: 5px;
		font-size: 16px;
		cursor: pointer;
		width: 100%;
		margin-bottom: 10px;
	}

	.binding-button:active {
		background-color: #0055ff;
	}

	.switch-btn-group {
		display: flex;
		gap: 10px;
		/* 按钮之间的间距 */
		margin-top: 5px;
		/* 与上方“绑定设备”按钮的间距 */
	}

	.switch-btn {
		flex: 1;
		/* 两个按钮平分容器宽度 */
		width: 60px;
		/* 固定宽度（确保正方形） */
		height: 60px;
		/* 固定高度（与宽度一致，实现正方形） */
		padding: 0;
		/* 清除默认内边距，避免文字偏移 */
		font-size: 18px;
		/* 按钮文字大小 */
		display: flex;
		/* 文字垂直居中 */
		align-items: center;
		/* 文字垂直居中 */
		justify-content: center;
		/* 文字水平居中 */
		background-color: #007aff;
		border-radius: 5px;
		/* 轻微圆角（可选，可改为0px实现直角正方形） */
		border: none;
		color: #fff;
	}

	.switch-btn:active {
		background-color: #0055ff;
		/* 点击时加深颜色，增强反馈 */
	}
</style>
